const path = require('node:path')

const getColumnsStr = (listVO, utils) => {
  const { properties } = listVO.jsonSchema
  const columnsStr = []

  for (const [prop, propConfig] of Object.entries(properties)) {
    const label = utils.extractText(propConfig.description)
    const width = label.length * 14 + 26
    columnsStr.push(
      `useTableColumnProps('${prop}', '${label}', { minWidth: ${width} })`
    )
  }
  return `const tableColumns: TableColumnProps<TableRow>[] = [${columnsStr.join(
    ','
  )}
]`
}

const getActionsStr = codeConfig => {
  const { modifyApiConfig, delApiConfig } = codeConfig.apiConfigStates

  return `
    const rowActions: TableRowActionsFunction<TableRow> = (row) => {
    const btnList = []
    ${
      modifyApiConfig ?
        `if (useAuth('${codeConfig.moduleName}Update')) {
      btnList.push({
        label: '编辑',
        click: handler.editActionHandler
      })
    }` :
        ''
    }
    ${
      delApiConfig ?
        `if (useAuth('${codeConfig.moduleName}Del')) {
      btnList.push({
        label: '删除',
        click: handler.delActionHandler
      })
    }` :
        ''
    }
    return btnList
  }`
}

module.exports = (codeConfig, utils) => {
  const { hasRowActions, listPageApiConfig } = codeConfig.apiConfigStates

  const listVO =
    codeConfig.dataSchemasNameMap[
      utils.extractGenericType(listPageApiConfig.response.schema.name)
    ]

  const { tableColumn } = require('../hooks/index.cjs')
  const code = `/* eslint-disable @typescript-eslint/no-unused-vars */
    import type { RowActionsInterface } from 'csui'
    import type { TableRow } from '../types'
    import ${tableColumn} from '/@/hooks/table-column'
    import useAuth from '/@/hooks/auth'
    ${hasRowActions ? "import type { useHandler } from './use-handler'" : ''}

    export const useTable = (${
      hasRowActions ? 'handler: ReturnType<typeof useHandler>' : ''
    }) => {
      ${getColumnsStr(listVO, utils)}
      ${getActionsStr(codeConfig)}

      return {
        tableColumns,
        rowActions
      }
    }
  `
  utils.writeFile(
    path.join(codeConfig.modulePath, 'hooks', 'use-table.ts'),
    code
  )
}
